<html>
<head>
<title>nTube: Settings</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--
	Theme Defaults:
	Colors: Black background, White foreground
	Font: Default Font used by Browser
-->
<style type="text/css" id="__ntheming_global">
html {
	background-color: black;
	color: white;
}
</style>
<style type="text/css" id="__ntheming_global_font">
html {
	font-family: sans-serif;
}
</style>
<style type="text/css">
select {
	color: inherit;
	background-color: inherit;
	font-family: inherit;
}

option {
	color: initial;
	background-color: inherit;
	font-family: inherit;
}

.collapsible {
  background-color: inherit;
  border: 1px solid green;
  color: inherit;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: left;
  outline: none;
  font-size: 15px;
  font-family: inherit;
}

.active, .collapsible:hover {
  background-color: #555;
}

.content {
  padding: 0 18px;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  background-color: inherit;
}

/*Checkboxes styles*/
input[type="checkbox"] { display: none; }

input[type="checkbox"] + label {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 20px;
  font: 14px/18px inherit;
  color: inherit;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

input[type="checkbox"] + label:last-child { margin-bottom: 0; }

input[type="checkbox"] + label:before {
  content: '';
  display: block;
  width: 20px;
  height: 20px;
  border: 1px solid #6cc0e5;
  position: absolute;
  left: 0;
  top: 0;
  opacity: .6;
  -webkit-transition: all .12s, border-color .08s;
  transition: all .12s, border-color .08s;
}

input[type="checkbox"]:checked + label:before {
  width: 10px;
  top: -5px;
  left: 5px;
  border-radius: 0;
  opacity: 1;
  border-top-color: transparent;
  border-left-color: transparent;
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
}
</style>
</head>
<body>
	<script type="text/javascript" >
function send_request(url, data, onFail, onSuccess) {
	if (typeof fetch != "undefined") {
		fetch(url).then(function(response) {
    		return response.text();
   	}).then(function(json) {
   		onSuccess(json);
   	}).catch(function(ex) {
   		console.error(ex);
   		console.error("Exception URL: " + url);
    		onFail();
  		});	
	}else {
		console.warn("send_request() -> Outdated browser found, attempting fallback method...");
		var http = null;
		if (window.XMLHttpRequest) {
			http = new XMLHttpRequest();		
		}else {
			http = new ActiveXObject("Microsoft.XMLHTTP");
		}
		http.open('POST', url, true);
	   http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	   
	   var hasResponse = false;
	   //var res = "";
	   http.onreadystatechange = function() {
		if (http.readyState == 4 && http.status == 200) {
		//		res = http.responseText;
				var sp = http.responseText.split("\n");
				onSuccess(sp[sp.length - 1]);
			}
		}
		http.ontimeout = function() {
			alert("nTube: onTimeout() was called when fetching your video!");
		}
		http.send(params);
	}
	//var http = new XMLHttpRequest();
	//var params = data;
	//http.timeout = 0;
	//http.responseType = 'blob';
	//http.open('POST', url, true);
	//http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			
	//var hasResponse = false;
	//var res = "";
	//http.onreadystatechange = function() {
	//	if (http.readyState == 4 && http.status == 200) {
	//		res = http.responseText;
	//		onSuccess(http.responseText);
	//	}
	//}
	//http.ontimeout = function() {
	//	alert("nTube: onTimeout() was called when fetching your video!");
	//}
	//http.send(params);
	
	/*		
	var stop = false;
	var time = 0;
	while (!hasResponse) {
		if (stop) {
			break;
		}
		if (time > 1500) {
			//alert("Timeout occured, try again.");
			onFail();
			stop = true;
		}
		var ix = -1;
		time += 1;
	}*/
}	

function b64DecodeUnicode(str) {
    try {
 		return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
        	return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    	}).join(''));   	
    }catch (ex) {
    	return atob(str);	
    }
}

function b64EncodeUnicode(str) {
    try {
 		return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode(parseInt(p1, 16))
    	}));
 	 }catch (ex) {
 	 	return btoa(str);
	 }
}

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    var val = value;
    if (value == null) {
		val = "null";    
    }else if (typeof value != "string") {
		val = value.toString();    
    }
    document.cookie = name + "=" + (val || "")  + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

function canStoreData() {
	return typeof Storage == "function" || navigator.cookieEnabled;
}

function readSettings() {
	if (!canStoreData()) {
		return null;	
	}
	if (localStorage.getItem("_ntube_settings") != null) {
		return localStorage.getItem("_ntube_settings");
	}else {
		return getCookie("settings");
	}	
}

function readSettingsToJSON() {
	var rs = readSettings();
	if (rs == null) {
		return null;	
	}
	return JSON.parse(b64DecodeUnicode(rs));
}

function writeSettingsFromJSON(jsonObject) {
	var enc = b64EncodeUnicode(JSON.stringify(jsonObject));
	setCookie("settings", enc, 9007199254740991);
	if (typeof Storage == "function") {
		localStorage.setItem("_ntube_settings", enc);	
	}
}

function writeSettings() {
	if (settingsObject == null) {
		var json_settings = {
			"looped": false,
			"useWebM": false,
			"preferQuality": -1,
			"desync": 4,
			"useDataPreloading": false,
			"subscriptions": [],
		};
		alert("/debug/:: write new profile");
		//writeSettingsFromJSON(settingsObject);
		return;
	}
	try {
		document.getElementById("__s_view").innerHTML = JSON.stringify(parsed);	
	}catch (ex) {
		document.getElementById("__s_view").innerHTML = "Couldn't load settings!";	
		document.getElementById("__s_view").style.color = "red";
	}
	writeSettingsFromJSON(settingsObject);
}

function loadSyncMode(jsonReference) {
	if (typeof jsonReference === "number") {
		console.warn("[nTube.loadSyncMode] WARNING: You are using the older sync storage mode, you should probably reset your config!");	
		var i = 0;
		var children = document.getElementById("__settings_sync_mode").children;
		for (; i < children.length; i++) {
			var child = children[i];
			var legacyOptionValue = child.attributes.getNamedItem("legacyoptionvalue");
			if (legacyOptionValue == jsonReference) {
				document.getElementById("__settings_sync_mode").selectedIndex = i;
				break;		
			}
		}
	}else {
		var i = 0;
		var children = document.getElementById("__settings_sync_mode").children;
		for (; i < children.length; i++) {
			var child = children[i];
			var newValue = child.attributes.getNamedItem("newvalue");
			if (newValue == jsonReference) {
				document.getElementById("__settings_sync_mode").selectedIndex = i;
				break;		
			}
		}
	}	
}

function applyTheme(themeCode) {
	console.log("[nTube: nTheming] Loading CSS for this page...");
	send_request("/api/get_css?eurl=" + themeCode, "", function () {
		console.error("[nTube: nTheming] Failed to load CSS!");
	}, function (data) {
		document.getElementById("__ntheming_global").innerHTML = data;
	});
}

function applyFont(fontCode) {
	console.log("[nTube: nTheming] Loading font for this page...");
	send_request("/api/get_font?eurl=" + fontCode, "", function () {
		console.error("[nTube: nTheming] Failed to load font!");
	}, function (data) {
		document.getElementById("__ntheming_global_font").innerHTML = data;
	});
}
	</script>
	<a href="/" style="font-size: x-large;text-decoration: none;"><span style="color: red;">n</span><span style="color: lightgreen;">Tube</span></a>
	<h3>Settings Configuration</h3>
	<center>
		<div style="border: 1px solid green;">
			<p style="display: inline-block;float: left;padding-left: 15px;">Can this browser store settings?</p>
			<p style="text-align: center;color: red;display: inline-block;float: right;padding-right: 15px;" id="__stor_test">NO</p>
			<div style="clear: both;"></div>
		</div>	
		<div style="border: 1px solid green;margin-bottom: 5px;">
			<p style="display: inline-block;float: left;padding-left: 15px;">Can this browser recieve notifications?</p>
			<p style="text-align: center;color: red;display: inline-block;float: right;padding-right: 15px;" id="__notif_test">NO</p>
			<div style="clear: both;"></div>
			<p style="font-size: small;color: gray;text-align: left;padding-left: 15px;line-height: 60%;">This is required for subscription notifications.</p>
		</div>	
	</center>
	<div>
		<button class="collapsible">Apperance</button>
		<div class="content">
 			<p>Global Theme: </p>
			<center>
			<select style="width: 75%;" id="__settings_theme_select" onChange="__lis_sq_theme();">
				<!--
					CSS themes are accquired via *url*/api/get_css?eurl=*eurl*
					Fonts are accquired via *url*/api/get_font?eurl=*eurl*
				-->
				<option eurl="defss">Black (default)</option>	
				<option eurl="inherss">Native</option>
				<option eurl="whitess">White</option>
				<option eurl="css_custom_carbon">Carbon</option>
				<option eurl="css_custom_phex">Purple Hexagons</option>
				<option eurl="css_custom_pcb">PCB (Printed Circuit Board)</option>
				<option eurl="css_custom_wheat">Wheat</option>
				<option eurl="css_custom_light_stripes">Light Stripes</option>
				<option eurl="css_custom_congruent_pentagon">Congruent Pentagon</option>
				<option eurl="css_custom_whatTheHex">What The Hex?! (Light)</option>
				<option eurl="css_custom_whatTheHex_dark">What The Hex?! (Dark)</option>
				<option eurl="css_custom_arches">Arches</option>
				<option eurl="css_custom_diagmonds">Diagmonds</option>
				<option eurl="css_custom_xv">xv</option>
				<option eurl="css_custom_christmas_colour">Christmas (Colour, WORK IN PROGRESS)</option>
				<option eurl="css_custom_christmas_dark">Christmas (Dark)</option>
				<option eurl="why">Questionable colours (WARNING: ALOT OF COLOURS, like 2)</option>
			</select>			
			<script type="text/javascript" >
			function __lis_sq_theme() {
				if (settingsObject != null) {
					var se = document.getElementById("__settings_theme_select");
					var sq = se.options[se.selectedIndex].attributes.getNamedItem("eurl").value;
					settingsObject.theme = sq;
					writeSettings();
					applyTheme(sq);
				}
			}
			</script>
			</center>
 			<p>Current Colors: </p>
 			<div>
				<center>
					<div style="width: 64px; height: 64px; display: inline-table;background-color: inherit;padding: 20px;border: 1px solid green;">			
						<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>					
					</div>
					<div style="width: 64px; height: 64px; display: inline-table;background-color: inherit;padding: 20px;border: 1px solid green;">
						<p>Foreground</p>				
					</div>
					<br>
					<p style="display: inline-table;padding: 5px;">Background Look</p>
					<p style="display: inline-table;padding: 5px;">Foreground Look</p>
				</center> 			
 			</div>
 			<p>Global Font</p>
 			<div>
				<center>
					<select style="width: 75%" id="__settings_font_select" onchange="__lis_sq_font();">
						<option eurl="font_default">Use Default Fonts (default)</option>
						<option eurl="font_monospace">Use Monospace Fonts</option>
						<option eurl="font_work_sans">Use Work Sans (via Google)</option>
						<option eurl="font_roboto">Use Roboto (via Google)</option>
						<option eurl="font_fira_sans">Use Fira Sans (via Google)</option>
						<option eurl="font_restricted_google_product_sans">Use Google Sans (Requires '--license.google.ps.allow' argument, Restricted license font)</option>
					</select>	
					<script type="text/javascript" >
					function __lis_sq_font() {
						if (settingsObject != null) {
							var se = document.getElementById("__settings_font_select");
							var sq = se.options[se.selectedIndex].attributes.getNamedItem("eurl").value;
							if (sq === "font_restricted_google_product_sans") {
								alert("By using this font you take full responsiblity for using a restricted font from Google, Inc.\n" + 
										"This font is a third party font is avaliable for sake but requires manual consent to use.\n" +
										"If the argument is not present, nTube falls back to the default option.");							
							}
							settingsObject.font = sq;
							writeSettings();
							applyFont(sq);
						}
					}
			</script>			
				</center> 			
 			</div>
 			<p style="font-family: monospace;">__REQUIRE("Appereance.polyMode")</p>
 			<p style="color: red; font-family: monospace;">
 				ERROR: Unable to find modules, leaving them as left by the developer.
 			</p>
			<p>The <b>NATIVE</b> theme will use the browsers colours.</p>
			<p>Users of frameworks (like GTK) can enable 'Use System Colours' in their browser settings to enable better theming.</p>
		</div> 
		<button class="collapsible">Extraction</button>
		<div class="content">
			<h4>This hasn't been implemented, these are merely placeholders for release 1.5.</h4>
			<p>Extraction Behaviour</p>
			<center>
				<div>
				</div>
			</center>
		</div>
		<button class="collapsible">Networking</button>
		<div class="content">
			<div>
				<div style="padding-top: 10px;">
						<input type="checkbox" id="box-1" style="float: right;" onclick="__lis_ds();">
						<label for="box-1" style="float: left;">Enable Data Saver</label>
						<script type="text/javascript" >
						function __lis_ds() {
							if (settingsObject != null) {
								settingsObject.useDataSaving = document.getElementById("box-1").checked;
								writeSettings();
							}
						}
						</script>
						<div style="clear: both;"></div>
				</div>	
				<div>
					<p>Data Saver, a feature for saving up precious data.</p>
 					<p>This feature was introduced during the nTube v1.4.4 beta.</p>
 					<p>When Enabled: </p>
 					<ul>
 						<li>Videos are automatically restricted to max. 360p</li>
 						<li>The trending tab <b style="color: red;">DOES NOT</b> load images. (~1MB saved)</li>
 						<li><b>ALL</b> thumbnails are set to the LOWEST quality. (120x90)</li>
 						<li>nTube will display a warning on playlists. (This shows up once per playlist)</li>
 						<li>Subscriptions will <b style="color: red;">NOT</b> be updated.</li>
 					</ul>				
				</div>	
				<div>
						<input type="checkbox" id="box-3" style="" onclick="__lis_preload();">
						<label for="box-3" style="">Enable Preloading<sub style="font-family: monospace;font-size: xx-small;">BETA</sub></label>	
						<script type="text/javascript" >
						function __lis_preload() {
							if (settingsObject != null) {
								settingsObject.useDataPreloading = document.getElementById("box-3").checked;
								writeSettings();
							}
						}
						</script>				
				</div>
				<div>
					<p>Preloading<sub style="font-family: monospace;font-size: xx-small;">BETA</sub> is an experimental feature that is used to speed up the process of loading videos.</p>				
				</div>
			</div>
		</div>
		<button class="collapsible">Notifications</button>
		<div class="content">
			<h3>These are purely placeholders, these are currently USELESS.</h3>
		</div>
		<button class="collapsible">Playback</button>
		<div class="content">
			<p style="display: inline-block;">nPlayer Version: </p>
			<p style="display: inline-block;float: right;">1.1.1</p>
			<div style="clear: both;"></div>
 			<div style="padding-top: 10px;">
						<input type="checkbox" id="box-2" style="float: right;" onclick="__lis_looped_videos();">
						<label for="box-2" style="float: left;">Loop Videos</label>
						<script type="text/javascript" >
						function __lis_looped_videos() {
							if (settingsObject != null) {
								settingsObject.looped = document.getElementById("box-2").checked;
								writeSettings();		
							}
						}
						</script>
						<div style="clear: both;"></div>
			</div>
			<div style="">
						<script type="text/javascript" >
						function __lis_webM_codec() {
							if (settingsObject != null) {
								settingsObject.useWebM = document.getElementById("box-4").checked;
								writeSettings();		
							}
						}
						</script>
						<input type="checkbox" id="box-4" style="" onclick="__lis_webM_codec();">
						<label for="box-4" style="">Allow the WebM codec to be used</label>
						<p>This option <b>MUST</b> be enabled to do the following: </p>
						<ul>
							<li>Videos with quality above 1080p</li>
							<li>Watch videos on non MP4 supporting browsers</li>						
						</ul>
			</div>
			<div style="padding-top: 10px;">
						<input disabled="true" type="checkbox" id="box-5" style="float: right;" onclick="">
						<label for="box-5" style="float: left;text-decoration: line-through;">Enable nPlayer VR/3D Support</label>
						<script type="text/javascript" >
						</script>
						<div style="clear: both;"></div>
			</div>
			<p>Video Synchronisation<sub style="font-family: monospace;font-size: xx-small;">via nPlayer</sub></p>
			<div style="border: 1px solid gray;">
				<p style="padding-left: 5px;">This only applies to videos that use nPlayer for playback. (i.e. 60FPS/1080p+/AV1)</p>				
				<center>
				<p style="display: inline;">Synchronisation mode:</p>
				<select onChange="__lis_smode();" id="__settings_sync_mode" style="display: inline;width: 80%;padding-left: 10px;padding-right: 10px;margin-bottom: 10px;">
					<option legacyOptionValue="4" newValue="sync.pf" readableValue="PerfectSync" maxDesync="120">PerfectSync (default)</option>
					<option legacyOptionValue="5" newValue="sync.pf.lite" readableValue="LiteSync" maxDesync="220">LiteSync (fork of PerfectSync, >220ms desync)</option>
					<option legacyOptionValue="0" newValue="sync.legacy" readableValue="Legacy" maxDesync="600">nSync 1.0 (legacy, >600ms desync)</option>
					<option legacyOptionValue="2" newValue="sync.legacy.minimal" readableValue="Legacy Minimal" maxDesync="400">nSync 1.0 (minimal mode) (legacy, >400ms desync)</option>
					<option legacyOptionValue="1" newValue="sync.legacy.older" readableValue="Legacy Old" maxDesync="1000">nSync 1.0 (legacy mode) (legacy, >1s desync)</option>
					<option legacyOptionValue="3" newValue="sync.disabled" readableValue="No Sync" maxDesync="500000">Disabled (up to 500 seconds of desync)</option>
					<option legacyOptionValue="-1" newValue="sync.native" readableValue="Native Browser Sync" maxDesync="-1" style="visibility: hidden;display: none;" disabled="true">Native Sync</option>				
				</select>	
				<script type="text/javascript" >
						function __lis_smode() {
							if (settingsObject != null) {
								var se = document.getElementById("__settings_sync_mode");
								var sq = parseInt(se.options[se.selectedIndex].attributes.getNamedItem("legacyOptionValue").value);
								settingsObject.desync = sq;
								writeSettings();		
							}
						}
					</script>				
				</center>
			</div>
			<p style="">Inital Video Quality</p>
			<p style="color: red;">WARNING: Qualities below 360p may fail to load. (Reasons include it being formatted as 3GPP or there not being an option)</p>
			<div style="border: 1px solid gray;">
				<center>
					<select onChange="__lis_vq();" id="__settings_vid_quality" style="width: 80%;padding-left: 10px;padding-right: 10px;margin-bottom: 10px;margin-top: 10px;">
						<option p="-1">Automatic (Highest Possible Quality)</option>
						<option p="4320">4320p (8K)</option>
						<option p="2160">2160p (4K)</option>
						<option p="1440">1440p (HD)</option>
						<option p="1080">1080p (HD)</option>
						<option p="720">720p (HD)</option>
						<option p="480">480p</option>
						<option p="360">360p</option>
						<option p="240">240p (WARNING: Sometimes 3GPP)</option>
						<option p="144">144p (WARNING: Sometimes 3GPP)</option>
					</select>
					<script type="text/javascript" >
						function __lis_vq() {
							if (settingsObject != null) {
								var se = document.getElementById("__settings_vid_quality");
								var sq = parseInt(se.options[se.selectedIndex].attributes.getNamedItem("p").value);
								//console.log("se=" + se);
								//console.log("se.options=" + se.options);
								//console.log("se.selectedIndex=" + se.selectedIndex);
								//console.log("sq=" + sq);
								settingsObject.preferQuality = sq;
								writeSettings();		
							}
						}
					</script>				
				</center>
			</div>
			<div style="padding-bottom: 25px;"></div>
		</div>
		<button class="collapsible">Privacy</button>
		<div class="content">
			<div style="padding-top: 10px;">
				<input disabled="true" type="checkbox" id="box-6" style="float: right;" onclick="">
				<label for="box-6" style="float: left;text-decoration: line-through;">Enable Privacy Mode</label>
				<script type="text/javascript" >
				</script>
				<div style="clear: both;"></div>
				<p>Not that nTube is not privacy caring enough but this just enables a much more aggresive protection aganist YouTube's tracking.</p>
				<p>Privacy Mode features:</p>
				<ul>
					<li>Cookie spoofing</li>
					<li>URL filtering</li>
					<li>Spoofed proxy headers</li>
				</ul>
			</div>
		</div>
		<button class="collapsible">nPlayer Changelog</button>
		<div class="content">
			<h3>1.1.1</h3>
			<ul>
				<li>Minor bug fixes.</li>
				<li>Added support for background playback on Chromium/Chrome based browsers.</li>
				<li>Fixed issue where the Player attempts to sync a single video.</li>
				<li>Added partial MediaGroup (NATIVE mode) support in hope that iOS Safari would be able to sync two streams.</li>
			</ul>
			<h3>1.1.0</h3>
			<ul>
				<li>The Player is now in a neat JavaScipt class and file. (/nplayer.js)</li>
				<li>Improved sync performance.</li>
				<li>Added option to switch to single or multiple sources.</li>
				<li>Added in-media source changing.</li>
				<li>Fixed issue where you couldn't phyiscally pause the video.</li>
			</ul>
			<h3>1.0.3-beta0</h3>
			<ul>
				<li>PerfectSync is now the default sync handler.</li>
				<li>Prepration for video player subtitle support.</li>
				<li>Prepartion for allowing in video quality switching.</li>
				<li>Added a debugging overlay. (Use $syncDebug for the moment to enable it)</li>			
			</ul>
			<h3>1.0.2</h3>
			<ul>
				<li>Added new experimental sync mode 'PerfectSync'.</li>
				<li>Added sync debug option.</li>
			</ul>
			<h3>1.0.1</h3>
			<ul>
				<li>Improved timings.</li>
				<li>Reduced overhead required.</li>		
				<li>Improved 60FPS support.</li>	
			</ul>
			<h3>1.0.0</h3>
			<ul>
				<li>Inital release.</li>			
			</ul>
		</div>
		<button class="collapsible">Settings Debug View</button>
		<div class="content">
			<p id="__s_view" style="font-family: monospace;overflow: auto;">Loading...</p>
		</div>
		<p style="padding-left: 5px;color: gray;font-size: small;font-family: monospace;">Fun Fact: You can click most of these boxes. (except the top one and the 2nd to top one telling above storing stuff)</p>
<script type="text/javascript" >
var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    var possHeight = content.attributes.getNamedItem("maxHeight");
    if (content.style.maxHeight) {
      content.style.maxHeight = null;
    } else if (possHeight != null) {
    	console.log(possHeight.value);
    	content.style.maxHeight = possHeight.value;
    } else {
      content.style.maxHeight = content.scrollHeight + "px";
    }
  });
}
</script>
<script type="text/javascript" >
if (canStoreData()) {
	document.getElementById("__stor_test").innerHTML = "YES";
	document.getElementById("__stor_test").style.color = "green";
}
if (window.Notification) {
	if (window.Notification.permission === "granted") {
		document.getElementById("__notif_test").innerHTML = "PERMISSION GRANTED";
		document.getElementById("__notif_test").style.color = "green";
	}else {
		document.getElementById("__notif_test").innerHTML = "PERMISSION PROMPTED (refresh after prompt)";
		document.getElementById("__notif_test").style.color = "orange";
		window.Notification.requestPermission().then(function (result) {
			if (result === "granted") {
				document.getElementById("__notif_test").innerHTML = "YES";
				document.getElementById("__notif_test").style.color = "green";
			}else {
				document.getElementById("__notif_test").innerHTML = "PERMISSION DENIED";
				document.getElementById("__notif_test").style.color = "red";
			}
		});
	}	
}else {
	document.getElementById("__notif_test").innerHTML = "UNSUPPORTED";
	document.getElementById("__notif_test").style.color = "red";
}
String.prototype.replaceAll = function(searchStr, replaceStr) {
	var str = this;

   // no match exists in string?
   if(str.indexOf(searchStr) === -1) {
      // return string
   	return str;
   }

   // replace and remove first match, and do another recursirve search/replace
	return (str.replace(searchStr, replaceStr)).replaceAll(searchStr, replaceStr);
}
String.prototype.contains = function(str) {
	return this.indexOf(str) > -1;
}
var set = readSettings();
var settingsObject = null;
if (set != null) {
	var parsed = JSON.parse(b64DecodeUnicode(set));
	settingsObject = parsed;
	try {
		document.getElementById("__s_view").innerHTML = JSON.stringify(parsed);	
	}catch (ex) {
		document.getElementById("__s_view").innerHTML = "Couldn't load settings!";	
		document.getElementById("__s_view").style.color = "red";
	}
	if (parsed.looped) {
		document.getElementById("box-2").checked = parsed.looped;	
	}
	if (parsed.useWebM) {
		document.getElementById("box-4").checked = parsed.useWebM;
	}
	if (parsed.useDataPreloading) {
		document.getElementById("box-3").checked = parsed.useDataPreloading;
	}
	if (parsed.useDataSaving) {
		document.getElementById("box-1").checked = parsed.useDataSaving;
	}
	if (parsed.preferQuality) {
		var se = document.getElementById("__settings_vid_quality");
		var i = 0;
		var opti = se.options;
		for (; i < opti.length; i++) {
			var item = opti[i];
			var p = item.attributes.getNamedItem("p").value;
			if (parseInt(p) == parsed.preferQuality) {
				se.selectedIndex = i;
				break;			
			}		
		}
	}
	if (parsed.desync) {
		var se = document.getElementById("__settings_sync_mode");
		var i = 0;
		var opti = se.options;
		for (; i < opti.length; i++) {
			var item = opti[i];
			var p = item.attributes.getNamedItem("legacyOptionValue").value;
			if (parseInt(p) == parsed.desync) {
				se.selectedIndex = i;
				break;			
			}		
		}
	}
	if (parsed.desync) {
		loadSyncMode(parsed.desync);	
	}
	if (parsed.theme) {
		applyTheme(parsed.theme);	
		var se = document.getElementById("__settings_theme_select");
		var i = 0;
		var opti = se.options;
		for (; i < opti.length; i++) {
			var item = opti[i];
			var p = item.attributes.getNamedItem("eurl").value;
			if (p == parsed.theme) {
				se.selectedIndex = i;
				break;			
			}		
		}
	}
	if (parsed.font) {
		applyFont(parsed.font);	
		var se = document.getElementById("__settings_font_select");
		var i = 0;
		var opti = se.options;
		for (; i < opti.length; i++) {
			var item = opti[i];
			var p = item.attributes.getNamedItem("eurl").value;
			if (p == parsed.font) {
				se.selectedIndex = i;
				break;			
			}		
		}
	}
	if (!parsed.subscriptions) {
		parsed.subscriptions = [];
	}
}else {
	/*
	 * subscription model:
	 * "subscriptions": [
	 *		{
	 *			"name": "Totally Not Clickbait!",
	 *			"channelID": "*cid*",
	 *			"lvid": "*lvid*",
	 *		}
	 *	],
	 */
	var json_settings = {
			"looped": false,
			"useWebM": false,
			"preferQuality": -1,
			"desync": 4,
			"useDataPreloading": false,
			"useDataSaving": false,
			"theme": "defss",
			"subscriptions": [],
	};
	writeSettingsFromJSON(json_settings);
	alert("Configuration created, we will now reload this page.")
	if (typeof window.reload === "function") {
		window.reload();	
	}else if (typeof window.location === "object") {
		window.location.reload();
	}else {
		alert("Sorry to interrupt, you need to reload manually for some reason.");
	}	
}
</script>
</body>
</html>
